<template>
  <div class="editor-container" p-20px>
    <el-form
      ref="editFormRef"
      :model="editData"
      :rules="menuFormRules"
      label-width="100px"
    >
      <el-form-item label="⻆⾊名称" prop="name">
        <el-input v-model="editData.name" placeholder="请输⼊⻆⾊名称" />
      </el-form-item>
      <el-form-item label="说明" prop="description">
        <el-input v-model="editData.description" placeholder="请输⼊说明" />
      </el-form-item>
      <el-form-item label="是否默认⻆⾊" prop="is_default"
        ><el-switch
          :active-value="1"
          :inactive-value="0"
          v-model="editData.is_default"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitMenuForm" :loading="loading"
          >提交</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import type { PropType } from "vue"
import { ElForm } from "element-plus"
import { IRole } from "@/api/role"
type FormInstance = InstanceType<typeof ElForm>
const emit = defineEmits(["submit"])
const props = defineProps({
  type: {
    type: Number,
    required: true
  },
  data: {
    type: Object as PropType<IRole>,
    default: () => ({})
  }
})

const loading = ref(false)
const editFormRef = useTemplateRef<FormInstance | null>("editFormRef")
const editData = ref({
  name: "",
  description: "",
  is_default: 0
})
// 验证规则
const menuFormRules = {
  name: {
    required: true,
    message: "请输⼊⻆⾊名称",
    trigger: "blur"
  },
  description: {
    required: true,
    message: "请输⼊说明",
    trigger: "blur"
  }
}

const defaultProps = {
  name: "",
  description: "",
  is_default: 0
}
// 表单重置和清除验证
const resetForm = () => {
  editData.value = { ...defaultProps, ...props.data }
  editFormRef.value?.clearValidate()
}

// 使⽤watchEffect监听数据变化
watchEffect(() => {
  if (props.data) {
    resetForm()
  }
})
// 提交表单
const submitMenuForm = () => {
  if (loading.value) return // 防⽌重复提交
  loading.value = true
  ;(editFormRef.value as FormInstance).validate((valid) => {
    if (valid) {
      emit("submit", editData.value)
    }
    loading.value = false
  })
}
</script>
